import  { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { ScrollView, View, Image, Text, Input } from '@tarojs/components'
import Iconfont from '@/components/Iconfont'
import { AtButton, AtMessage, AtNoticebar } from 'taro-ui'
import './index.scss'
import { connect } from 'react-redux'
import { upDatedDiyCategory } from '@/store/annual/action'
import { delayQuerySelector,throttle } from '@/utils'
import { getDiySpecUseList } from '@/api/annual'

type State = {
	disabled: boolean
	eachCount: any
  navIndex: number
  scrollTop: number
  goodsList: Array<any>
  categoryItem: any
  goodsPrice: any
}
@connect<any>(({ annual }) => ({ annual }), _dispatch => ({
  dispatchDiyList(data) {
    return _dispatch(upDatedDiyCategory(data))
  }
}))
export default class AnnualDiySpecIndex extends Component<any, State> {
  $instance = getCurrentInstance();
  protected bannerH: number
  protected bannerImg: string = `${SOURCES_PATH}/img/annual/banner.png`
  protected cartImg: string = `${SOURCES_PATH}/img/annual/cart.png`
  protected params: any
  protected goodsId: number | string
  constructor(props) {
    super(props)
    this.state = {
			disabled: true,
			eachCount: 1,
      navIndex: 0,
      scrollTop: 0,
			goodsList: [],
			categoryItem: {
				useNum: 1,
				goodsItems: []
			},
      goodsPrice: {
        price: '--',
        originPrice: '--'
      }
    }
  }
  static options = {
    addGlobalClass: true
  }

  onScroll(e) {

  }

  UNSAFE_componentWillMount() {
    delayQuerySelector(this, '.banner-wrap', 0).then(rect => {
      if (rect[0]) {
        this.bannerH = rect[0].height
      }
    })
  }

  componentDidMount() {
    const { params } = this.$instance.router
    this.params = params
    this.getDiySpecUseList(params)
  }

  async getDiySpecUseList(params: any, useNum: number = 0) {

		let { carModelMatchType, categoryCode, jekunModelCode, goodsId } = params
    Taro.showLoading({title: '匹配中'})
    try {
      let res = await getDiySpecUseList({
        query: {
          filter: {
            and: []
          }
        },
        goodsId,
        useNum,
        carModelMatchType,
        categoryCode,
        jekunModelCode
      })
      if (res.data.success) {
        this.setState({
          categoryItem: res.data.data
        }, () => {
          this.calcPrice()
        })
      }
    } catch (error) {

    } finally {
      Taro.hideLoading()
    }
  }

  async handleSubmit(e) {
    let { categoryItem } = this.state
    categoryItem.categoryKey = Number(this.params.categoryKey)
    categoryItem.parentKey = Number(this.params.parentKey)
    let goodsItems: Array<any> = []
    for (let i in categoryItem.goodsItems) {
      if (Number(categoryItem.goodsItems[i].num) !== 0) {
        goodsItems.push(categoryItem.goodsItems[i])
      }
    }
    categoryItem.goodsItems = goodsItems
    await this.props.dispatchDiyList(categoryItem)
		Taro.navigateBack({
			delta: 2
		})
	}

  handleAddCount() {
      let { categoryItem } = this.state
      categoryItem.useNum ++
      Taro.vibrateShort()
      this._updateList(	categoryItem.useNum)
  }
  handleReduceCount() {
      let { categoryItem } = this.state
      categoryItem.useNum --
      if (categoryItem.useNum < 1) {
    categoryItem.useNum = 1
    Taro.showToast({
      title: '最小保养用量为1哦～',
      icon: 'none'
    })
    return
  }
      Taro.vibrateShort()
      this._updateList(categoryItem.useNum)
  }
  handleChangeCount(e) {
      let { categoryItem } = this.state
      let baseEachBuy = categoryItem.useNum
      let { value } = e.target

      if (!value) {
          value = baseEachBuy
      }
      categoryItem.useNum = Math.ceil(Number(value))
      this._updateList(categoryItem.useNum)
      return String(value)
}
  _updateList = throttle((useNum) => {
      this.getDiySpecUseList(this.params, useNum)
  }, 500)

  calcPrice() {
    let { categoryItem } = this.state
    let [price, originPrice] = [0, 0]
    for (let i in categoryItem.goodsItems) {
      price += Number(categoryItem.goodsItems[i].goods.annualCardPrice) * Number(categoryItem.goodsItems[i].num)
      originPrice += Number(categoryItem.goodsItems[i].goods.platformPrice) * Number(categoryItem.goodsItems[i].num)
    }
    this.setState({
      goodsPrice: {
        price,
        originPrice
      }
    })

  }
  render() {
    const scrollStyle = {
      height: '100vh'
    }
    let { categoryItem, goodsPrice } = this.state
    return (
      <View className='annual-diy-spec-num-wrap'>
        <View className='btn-wrap'>
          <View className='price-wrap'>
            ￥<Text className='price'>{goodsPrice.price}</Text>
            <Text className='origin-price'>￥{goodsPrice.originPrice}</Text>
					</View>
					<View className='btn'>
						<AtButton type='primary' onClick={this.handleSubmit.bind(this)}>确认DIY</AtButton>
					</View>
        </View>
        <ScrollView className='list' scrollWithAnimation enableBackToTop scrollY onScroll={this.onScroll.bind(this)} style={scrollStyle}>
					<View className='info-wrap'>
						<AtNoticebar icon='alert-circle'>
							原厂推荐用油量：{ categoryItem.recommendUse }L
						</AtNoticebar>
						<View className='count'>
							<Text className='desc'>选择每次保养用量次/L</Text>
							<View className='input-num'>

								{/* <View className='down number-action' onClick={this.handleReduceCount.bind(this)}>-</View>
								<Input className='number' value={categoryItem.useNum} onInput={this.handleChangeCount.bind(this)} type='number' />
								<View className='up number-action' onClick={this.handleAddCount.bind(this)}>+</View>
								<View></View> */}
                <View className='down number-action' onTouchStart={this.handleReduceCount.bind(this)}>
                  { categoryItem.useNum <= 1 && <Iconfont size='24' color='#eee' name='icon-jian-gaoliang' /> }
                  { categoryItem.useNum > 1 && <Iconfont size='24' color='#333' name='icon-jian-gaoliang' /> }
                </View>
                <View  className='number'>{categoryItem.useNum}</View>
                <View className='up number-action' onTouchStart={this.handleAddCount.bind(this)}>
                  <Iconfont size='24' color='#fff' name='icon-jia-gaoliang' />
                </View>
                <View></View>
							</View>
						</View>
					</View>
          <View className='content-wrap'>

            {categoryItem.goodsItems.map((goods) =>
              <View className='item-info' key={goods.goodsId}>
                <View className='left'>
                  <Image className='annual-img' mode='aspectFill' lazyLoad src={goods.goods.thumbnailUrl}></Image>
                </View>
                <View className='right'>
                  <View className='goods-name'>
                    <Text className='goods-name-wrap'>
                    {goods.goods.goodsName}
                    </Text>
                  </View>
                  <View className='r-bottom-wrap'>
                    <View className='r-bottom-t'>
                      {goods.goods.tags && goods.goods.tags.length && <View className='tag'>{goods.goods.tags.join(',')}</View>}
                      <Text>已售出{goods.goods.saleCount}件</Text>
                    </View>
                    <View className='r-bottom-b'>
                      <View className='r-bottom-b-l'>
                        ￥<Text className='price'>{Number(goods.goods.annualCardPrice)}</Text>
                        <Text className='origin-price'>￥{goods.goods.platformPrice}</Text>
                      </View>
											<Text className='r-bottom-b-r'>x {goods.num}</Text>
                    </View>
                  </View>
                </View>
              </View>
            )}
          </View>
        </ScrollView>
        <AtMessage />
      </View>
    )
  }
}
